package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.gdpu.Service.StudentService;
import org.gdpu.Service.UserService;
import org.gdpu.model.User;
import org.gdpu.vo.UserVO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by HEWI2 on 2/17/14.
 */
@Component("login")
@Scope("prototype")
public class LoginAction extends MyActionSupport implements ModelDriven<UserVO> {

    private UserService userService;
    private StudentService studentService;
    private final UserVO userVO = new UserVO();

    private static final Logger logger = LogManager.getLogger(LoginAction.class);

    //用户登录
    @Override
    public String execute() throws Exception {

        if (userVO.getUserName().isEmpty() || userVO.getPassword().isEmpty()) {
            userVO.setResultMessage("请填写用户名密码！");
            return ERROR;
        }

        if (userVO.getPowerGroup().isEmpty()) {
            userVO.setResultMessage("请选择权限组！");
            return ERROR;
        }

        User user = userService.findByName(userVO.getUserName());
        if (user == null) {
            userVO.setResultMessage("用户不存在！");
            return ERROR;
        }
        logger.entry(user.getUserName());

        if (userVO.getPassword().equals(user.getPassword())) {
            if (user.getPowerGroup() == null) {
                userVO.setResultMessage("您还没有分配相应的角色,不存在任何权限!请找相关人士联系!");
                return ERROR;
            }

            if (!userVO.getPowerGroup().equals(user.getPowerGroup().getPowerGroup())) {
                userVO.setResultMessage("该用户不属于该角色！");
                return ERROR;
            }

            storePersonToSession(user);
            logger.info("user:" + user.getUserName() + ", group:"
                    + user.getPowerGroup().getPowerGroup() + " login the system.");

            if (!studentService.checkMonitor(user.getDormitory()) && "学生宿舍".equals(user.getPowerGroup().getPowerGroup())) {
                view = "/page/myDormitory/auto.jsp";
                return VIEW;
            }
            HttpServletRequest request = ServletActionContext.getRequest();
            Object obj = request.getSession().getAttribute("requestURI");
            if (obj != null) {
                view = obj.toString();
            } else {
                view = "/index.jsp";
                return VIEW;
            }
            logger.trace(obj.toString());
            return "view";

            //return SUCCESS;
        }
        logger.warn("用户:" + user.getUserName() + "   密码错误！");
        logger.exit(user.getUserName());
        userVO.setResultMessage("密码错误！");
        return ERROR;

    }

    public String loginOut() throws Exception {
        HttpSession session = ServletActionContext.getRequest().getSession();
        User person = (User) session.getAttribute("person");
        if (person != null) {
            logger.info(person.getUserName() + " leave the system by security way");
            session.removeAttribute("person");
            //session.invalidate();
        }
        view = "/login.jsp";
        return VIEW;
    }


    //忘记密码
    public String forget() {

        User person = userService.findByName(userVO.getUserName());
        if (person == null) {
            userVO.setResultMessage("该用户不存在！");
            return ERROR;
        }
        if (userVO.getDormitory().equals(person.getDormitory().getDormitoryId())) {
            userVO.setResultMessage("<script>alert('用户密码：" + person.getPassword() + "');location.href='login.jsp';</script>");
            return SUCCESS;
        }
        userVO.setResultMessage("用户信息有误！");
        return ERROR;
    }

    @Override
    public UserVO getModel() {
        return userVO;
    }

    @Resource(name = "userServiceImpl")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Resource(name = "studentServiceImpl")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    private void storePersonToSession(User target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        User storedPerson = (User) session.getAttribute("person");
        if (storedPerson == null || !storedPerson.equals(target)) {
            session.setAttribute("person", target);
            session.setAttribute("loginKey", "success");
            session.setMaxInactiveInterval(-1);
        }
    }
}

